from marshmallow import Schema, fields, validate, validates, ValidationError

class RoleSchema(Schema):
    """角色模式"""
    name = fields.Str(required=True, validate=validate.Length(min=2, max=50))
    displayName = fields.Str(validate=validate.Length(max=50))
    description = fields.Str(validate=validate.Length(max=200))
    permissions = fields.List(fields.Str())
    status = fields.Str(validate=validate.OneOf(['启用', '禁用']), load_default='启用')

    def validate_name(self, value, **kwargs):
        """验证角色名格式"""
        if not value.isalnum() and not '_' in value:
            raise ValidationError('角色名只能包含字母、数字和下划线')
        return value

class RoleUpdateSchema(Schema):
    """角色更新模式"""
    name = fields.Str(validate=validate.Length(min=2, max=50))
    displayName = fields.Str(validate=validate.Length(max=50))
    description = fields.Str(validate=validate.Length(max=200))
    permissions = fields.List(fields.Str())
    status = fields.Str(validate=validate.OneOf(['启用', '禁用']))

    def validate_name(self, value, **kwargs):
        """验证角色名格式"""
        if not value.isalnum() and not '_' in value:
            raise ValidationError('角色名只能包含字母、数字和下划线')
        return value 